package com.magicborrow.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.easemob.EMCallBack;
import com.easemob.chat.EMChatManager;
import com.magicborrow.Constants;
import com.magicborrow.MagicBorrowApplication;
import com.magicborrow.R;
import com.magicborrow.beans.UserBean;
import com.magicborrow.utils.MD5;
import com.magicborrow.utils.Md5Util;
import com.magicborrow.utils.UmengUtils;
import com.magicborrow.utils.UserTools;
import com.magicborrow.utils.VolleyTool;
import com.magicborrow.views.LoadingDialog;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.PushAgent;
import com.umeng.message.UmengRegistrar;

import java.util.HashMap;

/**
 * Created by Administrator on 2016/5/4.
 */
public class LonginActivity extends BaseActivity implements View.OnClickListener, TextWatcher, VolleyTool.HTTPListener {

    private TextView editPhone;
    private TextView editPassword;
    private Button btnLongin;
    private ImageView iv_back;
    private LoadingDialog dialog;
    private String password;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_longin);
        initView();
        initListener();
    }

    private void initView() {
        editPhone = (TextView) findViewById(R.id.edit_phone);
        editPassword = (TextView) findViewById(R.id.edit_password);
        btnLongin = (Button) findViewById(R.id.btn_longin);
        editPassword.addTextChangedListener(this);
        editPhone.addTextChangedListener(this);
        findViewById(R.id.tv_forgot_password).setOnClickListener(this);
        btnLongin.setEnabled(false);
        btnLongin.setAlpha(0.7f);
        iv_back = (ImageView) findViewById(R.id.imv_back);
    }

    private void initListener() {
        btnLongin.setOnClickListener(this);
        iv_back.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.imv_back:
                finish();
                break;
            case R.id.btn_longin:
                String phone = editPhone.getText().toString();
                String password = editPassword.getText().toString();
                password = MD5.getMD5(MD5.getMD5(password));
                HashMap<String, String> params = new HashMap<>();
                params.put("mobile", phone);
                params.put("password", password);
                params.put("deviceToken", UmengUtils.getToken(this));
                dialog = new LoadingDialog(this);
                dialog.show();
                VolleyTool.get(Constants.URL_GET_LOGIN, params, this, 0, UserBean.class);
                break;
            case R.id.tv_forgot_password:
                Intent intent = new Intent(this, VerticalCodeActivity.class);
                startActivity(intent);
                break;
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        String phone = editPhone.getText().toString();
        password = editPassword.getText().toString();
        if (phone == null || phone.length() != 11 || password == null || password.length() < 6) {
            btnLongin.setEnabled(false);
            btnLongin.setAlpha(0.7f);
        } else {
            btnLongin.setEnabled(true);
            btnLongin.setAlpha(1f);
        }
    }

    @Override
    public <T> void onResponse(T t, int requestCode) {
        dialog.dismiss();
        UserBean b = (UserBean) t;
        if (b.getCode() >= 0) {
            final UserBean.User user = b.getData();
            user.setPassword( MD5.getMD5(MD5.getMD5(password)));
            UserTools.saveUser(this, user);
            // 加个登陆试试
            EMChatManager.getInstance().login(user.getId() + "", MD5.getMD5(MD5.getMD5(password)), new EMCallBack() {
                @Override
                public void onSuccess() {
                    //  Toast.makeText(TaPageActivity.this, "chenggong" + MD5.getMD5(MD5.getMD5(user.getPassword())), Toast.LENGTH_SHORT).show();
                    // 登陆成功，保存用户名密码
                    MagicBorrowApplication.getInstance().setUserName(user.getId() + "");
                    MagicBorrowApplication.getInstance().setPassword(MD5.getMD5(MD5.getMD5(password)));

                    // 更新当前用户的nickname 此方法的作用是在ios离线推送时能够显示用户nick
                    boolean updatenick = EMChatManager.getInstance().updateCurrentUserNick(
                            user.getNickname());
                    Log.e("xxxxx", "登录成功  " + user.getId() + "");
                }

                int t = 0;

                @Override
                public void onError(int i, String s) {
                    Log.e("环信登录失败", s);
                    if (t < 4) {
                        EMChatManager.getInstance().login(user.getId() + "", MD5.getMD5(MD5.getMD5(password)), this);
                        t++;
                    }

                }

                @Override
                public void onProgress(int i, String s) {

                }
            });
            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
            finish();
        } else {
            showShortMsg(b.getMessage());
        }
    }

    @Override
    public void onErrorResponse(VolleyError error, int requestCode) {
        dialog.dismiss();
    }
}
